<template>
  <div class="chat-page">
    <!-- 聊天头部 -->
    <div class="chat-header mb-8">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-4">
          <NuxtLink to="/" class="text-slate-600 hover:text-slate-900 transition-colors">
            <el-icon class="text-xl"><ArrowLeft /></el-icon>
          </NuxtLink>
          <div>
            <h1 class="text-2xl font-bold text-slate-900">
              智能对话
            </h1>
            <p class="text-slate-600 mt-1">
              与AI助手对话，获取新闻数据分析
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 聊天界面 -->
            <div class="chat-container bg-white rounded-lg shadow-sm border border-slate-200 h-96 flex flex-col">
      <!-- 聊天消息区域 -->
      <div class="flex-1 p-6 overflow-y-auto">
                  <div v-if="messages.length === 0" class="flex items-center justify-center h-full text-slate-500">
          <div class="text-center">
            <el-icon class="text-4xl mb-4"><ChatDotRound /></el-icon>
            <p>开始与AI助手对话吧！</p>
            <p class="text-sm mt-2">你可以询问新闻趋势、数据分析等问题</p>
          </div>
        </div>
        
        <div v-else class="space-y-4">
          <div
            v-for="(message, index) in messages"
            :key="index"
            :class="[
              'flex',
              message.type === 'user' ? 'justify-end' : 'justify-start'
            ]"
          >
            <div
              :class="[
                'max-w-xs lg:max-w-md px-4 py-3 rounded-lg',
                message.type === 'user'
                  ? 'bg-blue-500 text-white'
                  : 'bg-slate-100 text-slate-900'
              ]"
            >
              <p class="text-sm whitespace-pre-wrap">{{ message.content }}</p>
              
              <!-- 显示数据 -->
              <div v-if="message.data && message.data.length > 0" class="mt-3">
                <div class="text-xs text-slate-500 mb-2">数据预览：</div>
                <div class="bg-white p-2 rounded border text-xs">
                  <pre>{{ JSON.stringify(message.data, null, 2) }}</pre>
                </div>
              </div>
              
              <!-- 显示图表 -->
              <div v-if="message.chartConfig" class="mt-3">
                <div class="text-xs text-slate-500 mb-2">图表：</div>
                <div class="bg-white p-2 rounded border">
                  <ChartRenderer 
                    :chart-config="message.chartConfig" 
                    :data="message.data"
                    :key="`chart-${index}`"
                  />
                </div>
              </div>
              
              <!-- 加载状态 -->
              <div v-if="message.loading" class="mt-2">
                <div class="flex items-center space-x-2 text-xs text-slate-500">
                  <div class="w-2 h-2 bg-slate-400 rounded-full animate-bounce"></div>
                  <div class="w-2 h-2 bg-slate-400 rounded-full animate-bounce" style="animation-delay: 0.1s"></div>
                  <div class="w-2 h-2 bg-slate-400 rounded-full animate-bounce" style="animation-delay: 0.2s"></div>
                  <span>正在分析...</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
              <div class="border-t border-slate-200 p-4">
        <div class="flex space-x-2">
          <el-input
            v-model="inputMessage"
            placeholder="输入你的问题..."
            class="flex-1"
            @keyup.enter="sendMessage"
          />
          <el-button type="primary" @click="sendMessage" :loading="sending">
            发送
          </el-button>
        </div>
      </div>
    </div>

    <!-- 功能提示 -->
    <div class="mt-8">
      <el-card class="bg-slate-50">
        <template #header>
          <div class="flex items-center">
            <el-icon class="mr-2"><ChatDotRound /></el-icon>
            <span>功能提示</span>
          </div>
        </template>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <div class="flex items-start space-x-2">
            <el-icon class="text-blue-500 mt-1"><TrendCharts /></el-icon>
            <div>
              <h4 class="font-medium">新闻趋势分析</h4>
              <p class="text-sm text-slate-600">了解热门话题和趋势变化</p>
            </div>
          </div>
          <div class="flex items-start space-x-2">
            <el-icon class="text-green-500 mt-1"><DataAnalysis /></el-icon>
            <div>
              <h4 class="font-medium">数据统计</h4>
              <p class="text-sm text-slate-600">获取新闻数量和分类统计</p>
            </div>
          </div>
          <div class="flex items-start space-x-2">
            <el-icon class="text-purple-500 mt-1"><Search /></el-icon>
            <div>
              <h4 class="font-medium">智能搜索</h4>
              <p class="text-sm text-slate-600">用自然语言搜索相关新闻</p>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ChatDotRound, TrendCharts, DataAnalysis, Search } from '@element-plus/icons-vue'
import ChartRenderer from '~/components/ChartRenderer.vue'

// 路由
const route = useRoute()

// 响应式数据
const messages = ref([])
const inputMessage = ref('')
const sending = ref(false)

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim()) {
    return
  }

  const userMessage = inputMessage.value.trim()
  
  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage
  })

  // 清空输入框
  inputMessage.value = ''
  sending.value = true

  try {
    // 调用真实的ChatBI服务
    await callChatBIService(userMessage)
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送失败，请稍后重试')
    sending.value = false
  }
}

// 调用ChatBI服务
const callChatBIService = async (query) => {
  const sessionId = 'chatbi-session-' + Date.now()
  
  // 添加AI消息占位符
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '正在分析数据...',
    loading: true,
    data: null,
    chartConfig: null
  })

  try {
    const response = await fetch('http://localhost:8080/api/ai/bi/query-stream', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: query,
        sessionId: sessionId,
        timeRange: 'week',
        chartType: 'auto',
        maxRecords: 100,
        includeSql: false,
        includeSummary: true
      })
    })

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let aiContent = ''
    let currentData = null
    let currentChartConfig = null
    let buffer = ''
    let currentEvent = null
    let pendingData = ''
    let summaryReceived = false
    let chartDataReceived = false

    while (true) {
      const { done, value } = await reader.read()
      
      if (done) break
      
      // 解码并添加到缓冲区
      buffer += decoder.decode(value, { stream: true })
      
      // 按行分割并处理
      const lines = buffer.split('\n')
      
      // 保留最后一行（可能不完整）
      buffer = lines.pop() || ''
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]
        const trimmedLine = line.trim()
        if (!trimmedLine) continue
        
        if (trimmedLine.startsWith('event:')) {
          // 如果有待处理的数据，先处理它
          if (pendingData && currentEvent) {
            const result = processEventData(currentEvent, pendingData, aiMessageIndex, aiContent, currentData, currentChartConfig)
            if (result) {
              aiContent = result.aiContent
              currentData = result.currentData
              currentChartConfig = result.currentChartConfig
            }
            pendingData = ''
          }
          
          const eventType = trimmedLine.substring(6).trim()
          currentEvent = eventType
          console.log('收到SSE事件:', eventType)
          
          // 处理不同的事件类型
          if (eventType === 'start') {
            aiContent = '开始处理查询...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'sql_generation') {
            aiContent += '正在生成SQL查询...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'sql_llm') {
            aiContent += '使用AI生成SQL...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'sql_optimized') {
            aiContent += 'SQL已优化...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'query_execution') {
            aiContent += '正在执行数据库查询...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'summary_generation') {
            aiContent += '正在生成数据洞察...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'chart_generation') {
            aiContent += '正在生成图表配置...\n'
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig)
          } else if (eventType === 'complete') {
            aiContent += '处理完成！\n'
            // 如果图表数据已接收，现在可以渲染图表
            if (chartDataReceived && currentChartConfig) {
              aiContent += '\n图表数据已准备完毕，正在渲染...\n'
            }
            updateAIMessage(aiMessageIndex, aiContent, currentData, currentChartConfig, false)
            sending.value = false
            return
          }
          
        } else if (trimmedLine.startsWith('data:')) {
          const dataContent = trimmedLine.substring(5).trim()
          if (!dataContent) continue
          
          // 检查下一个事件是否在同一批次中
          let nextEventInBatch = false
          for (let j = i + 1; j < lines.length; j++) {
            if (lines[j].trim().startsWith('event:')) {
              nextEventInBatch = true
              break
            }
          }
          
          if (nextEventInBatch) {
            // 如果下一个事件在同一批次中，立即处理数据
            const result = processEventData(currentEvent, dataContent, aiMessageIndex, aiContent, currentData, currentChartConfig)
            if (result) {
              aiContent = result.aiContent
              currentData = result.currentData
              currentChartConfig = result.currentChartConfig
            }
          } else {
            // 否则等待下一个事件
            pendingData = dataContent
          }
        }
      }
    }
    
    // 处理最后的数据
    if (pendingData && currentEvent) {
      const result = processEventData(currentEvent, pendingData, aiMessageIndex, aiContent, currentData, currentChartConfig)
      if (result) {
        aiContent = result.aiContent
        currentData = result.currentData
        currentChartConfig = result.currentChartConfig
      }
    }
    
  } catch (error) {
    console.error('ChatBI服务调用失败:', error)
    messages.value[aiMessageIndex].content = '抱歉，服务暂时不可用，请稍后重试。'
    messages.value[aiMessageIndex].loading = false
    sending.value = false
  }
}

// 处理事件数据
const processEventData = (eventType, dataContent, aiMessageIndex, aiContent, currentData, currentChartConfig) => {
  try {
    let newAiContent = aiContent
    let newCurrentData = currentData
    let newCurrentChartConfig = currentChartConfig
    
    if (eventType === 'sql_generated') {
      newAiContent += `\n生成的SQL:\n\`\`\`sql\n${dataContent}\n\`\`\`\n`
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'query_completed') {
      newAiContent += `\n${dataContent}\n`
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'data_ready') {
      const data = JSON.parse(dataContent)
      newCurrentData = data.data
      newAiContent += `\n查询结果：共返回 ${data.totalRows} 条记录\n`
      if (data.data && data.data.length > 0) {
        newAiContent += `\n数据预览：\n\`\`\`json\n${JSON.stringify(data.data.slice(0, 3), null, 2)}\n\`\`\`\n`
      }
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'chart_ready') {
      const chartConfig = JSON.parse(dataContent)
      newCurrentChartConfig = chartConfig
      // 标记图表数据已接收，但不立即渲染
      newAiContent += '\n图表配置已准备完毕，等待完整数据加载...\n'
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'chart_skipped') {
      const skipInfo = JSON.parse(dataContent)
      newAiContent += `\n图表生成已跳过：${skipInfo.reason}\n`
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'summary_ready') {
      // 总结内容作为主要内容显示，优先展示
      newAiContent = dataContent + '\n\n' + newAiContent
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    } else if (eventType === 'error') {
      newAiContent += `\n错误：${dataContent}\n`
      updateAIMessage(aiMessageIndex, newAiContent, newCurrentData, newCurrentChartConfig)
    }
    
    return {
      aiContent: newAiContent,
      currentData: newCurrentData,
      currentChartConfig: newCurrentChartConfig
    }
  } catch (e) {
    console.error('解析数据失败:', e, '数据内容:', dataContent)
    return null
  }
}

// 更新AI消息
const updateAIMessage = (index, content, data, chartConfig, loading = true) => {
  messages.value[index] = {
    type: 'ai',
    content: content,
    loading: loading,
    data: data,
    chartConfig: chartConfig
  }
}

// 页面加载时检查是否有初始查询
onMounted(() => {
  const query = route.query.query
  if (query) {
    inputMessage.value = query
    sendMessage()
  }
})
</script>

<style scoped>
.chat-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 1rem;
}

.chat-container {
  min-height: 400px;
}

/* 滚动条样式 */
.chat-container .overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.chat-container .overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.chat-container .overflow-y-auto::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.chat-container .overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 深色模式滚动条 */

</style>

